const express = require('express');
let router = express.Router();

//日志
const {
    logger
} = require('../../config/logger');

const Response = require('../../utils/response')

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const noteQuery = require('../../db/noteQuery/noteQuery');

//解析token
const {
    token_verify
} = require('../../config/jwt')

//引入时间模块
const sd = require('silly-datetime');

//引入scoket通知
const {
    sendSystemMessage_note
} = require('../../notice/auditNotice')

//获取小纸条信息详细
router.get('/detailed', function (req, res) {
    const noteId = req.query.noteId;
    pool.query(noteQuery.select_note, noteId, (error, result) => {
        if (error) {
            logger().error(`获取小纸条信息详细错误: ${error}`);
            res.json(Response.error("获取小纸条详细信息失败", null));
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取小纸条详细信息成功", data));
        }
    });
})

//发送小纸条
router.post('/send', function (req, res) {
    const token = req.headers.authorization;
    const receiver = req.body.receiver; //houseID
    const content = req.body.content;
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    const {
        userId,
        role
    } = token_verify(token);
    pool.query(noteQuery.select_userId, receiver, (error, result) => {
        if (error) {
            res.json(Response.error("发送小纸条失败", null));
            logger().error(`发送小纸条错误: ${error}`);
        } else {
            //获取接收者userID
            const {
                houseHold_userId
            } = JSON.parse(JSON.stringify(result[0]));
            pool.query(noteQuery.getUser_name, userId, (error, result) => {
                if (error) {
                    res.json(Response.error("发送小纸条失败", null));
                    logger().error(`发送小纸条错误: ${error}`);
                } else {
                    //获取发送人昵称
                    const {
                        nickName
                    } = JSON.parse(JSON.stringify(result[0]))
                    //获取接收者的openid
                    pool.query(noteQuery.getReceiver_openId, houseHold_userId, (error, result) => {
                        if (error) {
                            res.json(Response.error("发送小纸条失败", null));
                            logger().error(`发送小纸条错误: ${error}`);
                            return;
                        } else {
                            //接收者的openid
                            const {
                                openid
                            } = JSON.parse(JSON.stringify(result[0]));
                            //用户角色为业主
                            if (role == 1) {
                                //纸条记录存档
                                pool.query(noteQuery.insert_note, [userId, receiver, content, time], (error, result) => {
                                    if (error) {
                                        res.json(Response.error("发送小纸条失败", null));
                                        logger().error(`发送小纸条错误: ${error}`);
                                        return;
                                    } else {
                                        const noteId = result.insertId;
                                        res.json(Response.success("发送小纸条成功", null));
                                        sendSystemMessage_note(houseHold_userId, {
                                            openId: openid,
                                            message: "您有一则小纸条消息",
                                            sender: nickName,
                                            content,
                                            time,
                                            noteId
                                        });
                                    }
                                });
                            }
                            //用户角色为租客
                            else if (role == 2) {
                                pool.query(noteQuery.getHousehold, userId, (error, result) => {
                                    if (error) {
                                        res.json(Response.error("发送小纸条失败", null));
                                        logger().error(`发送小纸条错误: ${error}`);
                                        return;
                                    } else {
                                        const {
                                            houseHold_userIds,
                                            houseHold_openId
                                        } = JSON.parse(JSON.stringify(result[0]));
                                        pool.query(noteQuery.insert_note, [userId, houseHold_userId, content, time], (error, result) => {
                                            if (error) {
                                                res.json(Response.error("发送小纸条失败", null));
                                                logger().error(`发送小纸条错误: ${error}`);
                                                return;
                                            } else {
                                                const noteId = result.insertId;
                                                //向接收者发送小纸条
                                                sendSystemMessage_note(houseHold_userId, {
                                                    openId: openid,
                                                    message: "您有一则小纸条消息",
                                                    sender: nickName,
                                                    content,
                                                    time,
                                                    noteId
                                                });
                                            }
                                        });
                                        pool.query(noteQuery.insert_note, [userId, houseHold_userIds, content, time], (error, result) => {
                                            if (error) {
                                                res.json(Response.error("发送小纸条失败", null));
                                                logger().error(`发送小纸条错误: ${error}`);
                                                return;
                                            } else {
                                                const noteId = result.insertId;
                                                res.json(Response.success("发送小纸条成功", null));
                                                //向房东者发送小纸条
                                                sendSystemMessage_note(houseHold_userIds, {
                                                    openId: houseHold_openId,
                                                    message: "租客向邻居发送了小纸条消息",
                                                    sender: nickName,
                                                    content: `租客向邻居发送：${content}`,
                                                    time,
                                                    noteId
                                                });
                                            }
                                        });
                                    }
                                });
                            }
                        }
                    });
                }
            });
        }
    });

})

//查看我发送的小纸条
router.get('/myDetailed', function (req, res) {
    const count = req.query.count ? parseInt(req.query.count) : 10;
    const page = req.query.page ? parseInt((req.query.page)) - 1 : 0;
    const token = req.headers.authorization;
    const {
        userId,
    } = token_verify(token);
    pool.query(noteQuery.select_myNote, [userId, count, page], (error, result) => {
        if (error) {
            res.json(Response.error("查看我发送的小纸条信息失败", null));
            logger().error(`查看我发送的小纸条错误: ${error}`);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("查看我发送的小纸条信息成功", data));
        }
    });
})

module.exports = router;